﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using AgileDashboard.Entities;
using AgileDashboard.Data.Converters;

namespace AgileDashboard.Data
{
    public class QueryDataSource
    {




        private void GetNodesForQueryFolder(QueryFolder queryFolder, List<QueryDefinition> queries)
        {


            foreach (QueryItem queryItem in queryFolder)
            {
                if (queryItem is QueryFolder)
                {
                    GetNodesForQueryFolder(queryItem as QueryFolder, queries);
                }
                else
                {
                    //if its not personal and its a list.
                    //if (!queryItem.IsPersonal)// && ((QueryDefinition)queryItem).QueryType == QueryType.List)
                    queries.Add((QueryDefinition)queryItem);
                }
            }
        }



        public List<QueryDefinition> GetQueryList(Project project)
        {
            List<QueryDefinition> queries = new List<QueryDefinition>();


            foreach (QueryItem queryItem in project.QueryHierarchy)
            {
                GetNodesForQueryFolder(queryItem as QueryFolder, queries);
            }

            return queries;

        }

        public string GetQueryTextFromQuery(Guid queryId, Project proj)
        {
            List<QueryDefinition> queries = GetQueryList(proj);

            return GetQueryTextFromQuery(queryId, queries);

        }



        public string GetQueryTextFromQuery(Guid queryId, List<QueryDefinition> queries)
        {

            foreach (QueryDefinition query in queries)
                if (query.Id == queryId)
                    return query.QueryText;

            return null;

        }


        public List<TfsQuery> GetQueries(Project proj)
        {
            List<TfsQuery> myQueryList = new List<TfsQuery>();

            List<QueryDefinition> queries = GetQueryList(proj);

            foreach (QueryDefinition queryDef in queries)
            {
                myQueryList.Add(ConverterHelpers.ConvertQuery(queryDef));

            }

            return myQueryList;

        }

    }
}
